package com.tool4j.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.io.IoUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.tool4j.entity.TemplateFile;
import com.tool4j.entity.TemplateInfo;
import com.tool4j.mapper.TemplateFileMapper;
import com.tool4j.service.TemplateFileService;
import com.tool4j.util.velocity.VelocityTemplateLoader;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.BufferedReader;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;

/**
 * @author Deng.Weiping
 * @since 2024/9/2 13:13
 */
@Service
public class TemplateFileServiceImpl extends ServiceImpl<TemplateFileMapper, TemplateFile> implements TemplateFileService {

    @Autowired
    private TemplateFileMapper templateFileMapper;

    @Override
    public List<TemplateFile> findByTemplateId(Long templateId) {
        LambdaQueryWrapper<TemplateFile> query = Wrappers.lambdaQuery(TemplateFile.class)
                .eq(TemplateFile::getTemplateId, templateId);
        return templateFileMapper.selectList(query);
    }

    @Override
    public List<TemplateFile> getTemplateContent(TemplateInfo templateInfo) {
        List<TemplateFile> templateFiles = findFilesByTemplateId(templateInfo.getId());
        String templateDir = String.format("%s/%s", VelocityTemplateLoader.getRootPath(), templateInfo.getPath());
        List<TemplateFile> files = new ArrayList<>();
        templateFiles.forEach(item -> {
            TemplateFile fileInfo = BeanUtil.toBean(item, TemplateFile.class);
            if (fileInfo.getLeaf()) {
                String filePath = String.format("%s/%s/%s", templateDir, fileInfo.getFilePath(), fileInfo.getFileName());
                try (InputStream input = FileUtil.getInputStream(filePath)) {
                    BufferedReader reader = IoUtil.getUtf8Reader(input);
                    StringBuffer buffer = new StringBuffer();
                    reader.lines().forEach(line -> buffer.append(line).append(StrUtil.LF));
                    reader.close();
                    fileInfo.setContent(buffer.toString());
                } catch (Exception e) {
                    log.error("文件读取失败");
                }
            }
            files.add(fileInfo);
        });
        return files;
    }

    @Override
    public List<TemplateFile> findFilesByTemplateId(Long templateId) {
        LambdaQueryWrapper<TemplateFile> query = Wrappers.lambdaQuery(TemplateFile.class)
                .eq(TemplateFile::getLeaf, true)
                .eq(TemplateFile::getTemplateId, templateId);
        return templateFileMapper.selectList(query);
    }

    @Override
    public void deleteById(Long fileId) {
        templateFileMapper.deleteById(fileId);
    }

    @Override
    public void deleteByIds(Set<Long> ids) {
        templateFileMapper.deleteBatchIds(ids);
    }

    @Override
    public void saveFiles(Long templateId, List<TemplateFile> files) {
        for (TemplateFile file : files) {
            file.setId(null);
            file.setTemplateId(templateId);
            save(file);
        }
    }

    @Override
    public boolean existsFile(String key, Long templateId) {
        LambdaQueryWrapper<TemplateFile> query = Wrappers.lambdaQuery(TemplateFile.class)
                .eq(TemplateFile::getKey, key)
                .eq(TemplateFile::getTemplateId, templateId);
        return CollUtil.isNotEmpty(templateFileMapper.selectList(query));
    }
}
